package Native::DataCollector;

use strict;
use warnings;
use 5.010;

use Encode 'decode';
use Exporter qw(import);
use Utils::Constants;
use Mojo::Log;
use Pojo::File;
use Mojo::Asset::File;
use File::Path qw(remove_tree);

my $log = Mojo::Log->new;

sub collect_current_home_temperature {
	return 28.4;
}

sub collect_current_home_brightness_status {
	return Utils::Constants::HOME_STATUS_OK;
}

sub collect_current_home_firesafety_status {
	return Utils::Constants::HOME_STATUS_OK;
}

sub collect_current_pi_cpu_temperature {
	return 41.4;
}

sub collect_current_pi_gpu_temperature {
	return 42.5;
}

sub collect_current_cpu_usage {
	return 51;
}

sub collect_current_memory_usage {
	return 62;
}

sub collect_current_system_load {
	return Utils::Constants::HOME_STATUS_OK;
}

sub collect_current_system_uptime {
	return '10:28';
}

sub generate_temperature_linechart {
    my $sql = "select time,value from t_temperature where date('now')=strftime('%Y-%m-%d',time)";
    my $data_filename = "temperature.dat";
    my $gp_filename = "temp_stats.gp";
    my $image_filename = Utils::Constants::TEMPERATURE_STATS_PICTURE;

    return query_and_generate_stats_picture($sql, $data_filename, $gp_filename, $image_filename);
}

sub generate_current_bloodsugar_linechart {
    my ($user_id) = @_;
    my $sql = "select time,value from t_bloodsugar where user_id = $user_id and date('now')=date order by date(date) ASC,time(time) ASC limit 20;";
    my $data_filename = "bloodsugar.dat";
    my $gp_filename = "sugar_stats.gp";
    my $image_filename = Utils::Constants::BLOODSUGAR_STATS_IMAGE;

    return query_and_generate_stats_picture($sql, $data_filename, $gp_filename, $image_filename);
}

sub query_and_generate_stats_picture {
    my ($sql, $data_filename, $gp_filename, $image_filename) = @_;
    my $sqldump_result_code = 1;
    my $plot_result_code = 1;

    system("sqlite3 data/data.db \"$sql\" > /tmp/$data_filename");  
    if ($? == -1) {
        $log->debug("Dumping sqlite data failed: $!");
    }
    elsif (($? >> 8) == 0) {
        $sqldump_result_code = ($? >> 8);
        system("gnuplot scripts/$gp_filename > public/images/$image_filename");
        if ($? == -1) {
            $log->debug("Plotting line chart failed: $!");
        }
        else {
            $plot_result_code = ($? >> 8);
        }
    }

    return $sqldump_result_code + $plot_result_code == 0 ? 1 : 0;
}

sub list_files_in_dir {
    my ($dir) = @_; 
    my @files = ();
    my $full_path = Utils::Constants::CLOUD_FILE_PATH_ROOT."$dir";

    $log->debug("Reading Path: $full_path");

    opendir(DIR, "$full_path")
            or $log->debug("File path error: $!") && return @files;
        
    while (my $file = readdir(DIR)) {
        next if ($file =~ m/^\./);
        my $item = Pojo::File->new();
        # We have to decode it, or any non-English characters, like Chinese, will be malformed junks
        my $file = decode('utf8', $file);

        $item->_set_name($file);
        $item->_set_type(  
                            (-d "$full_path/$file") ? 
                            Utils::Constants::FILE_TYPE_DIRECTORY : 
                            Utils::Constants::FILE_TYPE_COMMON
                        );

        push @files, $item;
    }

    closedir(DIR);

    return @files;
}

sub get_file_by_path {
    my $path = shift;
    my $full_path = Utils::Constants::CLOUD_FILE_PATH_ROOT."$path";

    $log->debug("Reading full path: $full_path");

    return undef unless -f "$full_path";

    return Mojo::Asset::File->new(path => "$full_path");
}

sub remove_file_by_path {
    my $path = shift;
    my $full_path = Utils::Constants::CLOUD_FILE_PATH_ROOT."$path";
    my $is_removed_success = (-d "$full_path") ? remove_tree("$full_path") : unlink "$full_path";

    $log->debug("Trying to remove file: $full_path\nResult: $is_removed_success");

    return $is_removed_success;
}

sub rename_file_by_path {
    my $ori_path = shift;
    my $new_path = shift;
    my $ori_full_path = Utils::Constants::CLOUD_FILE_PATH_ROOT."$ori_path";
    my $new_full_path = Utils::Constants::CLOUD_FILE_PATH_ROOT."$new_path";
    my $is_rename_success = rename "$ori_full_path", "$new_full_path";

    $log->debug("Trying to rename file: $ori_full_path to $new_full_path\nResult: $is_rename_success");

    return $is_rename_success;
}

sub store_file_by_path {
    my ($path, $filename, $file) = @_;
    my $full_path = Utils::Constants::CLOUD_FILE_PATH_ROOT."$path";
    
    return save_to($full_path, $filename, $file);
}

sub save_static_file {
    my ($path, $filename, $file) = @_;
    my $full_path = "public/$path";

    return save_to($full_path, $filename, $file);
}

sub add_new_folder {
    my ($path, $dir_name) = @_;
    my $full_path = Utils::Constants::CLOUD_FILE_PATH_ROOT."$path";

    mkdir "$full_path" unless -d "$full_path";
    my $result = mkdir "$full_path/$dir_name";
   
    $log->debug($full_path);
    return $result;
}

sub save_to {
    my ($path, $filename, $file) = @_;
    
    mkdir "$path" unless -d "$path";

    $file->move_to("$path/$filename");

    return -f "$path/$filename";
}

1;
